package com.liu.netty.demo.client;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import lombok.extern.slf4j.Slf4j;

/**
 * netty源代码，版权归锦翰科技（深圳）有限公司所有。
 * <p>
 * 文件名称 : GoJsonRpcClient
 * 文件路径 : com.liu.netty.demo.client
 * 作者 : DavidLiu
 * × Email: david.liu@ginghan.com
 * <p>
 * 创建日期 : 2022/3/27 22:13
 * 修改历史 : 1. [2022/3/27 22:13] 创建文件 by NST
 */

@Slf4j
public class GoJsonRpcClient{

    public static void main(String[] args){
        DemoClient dc = new DemoClient("192.168.56.101", 8096){

            @Override
            protected ChannelHandler[] initHandlers() {
                ChannelHandler[] channelHandlers = {
                        new StringDecoder(),
                        new StringEncoder(),
                        new SimpleChannelInboundHandler<String>() {

                            @Override
                            public void channelActive(ChannelHandlerContext ctx) throws Exception{
                                String request = "{\"id\":1000,\"method\":\"Arith.Multiply\",\"params\":[{\"A\":9,\"B\":2}]}";

                                ctx.channel().writeAndFlush(request);

                                super.channelActive(ctx);
                            }

                            @Override
                            protected void messageReceived(ChannelHandlerContext ctx, String msg) throws Exception {

                                log.info(msg);

                                ctx.close();

                                getWorker().shutdownGracefully();

                                //ctx.fireChannelRead(msg);
                            }
                        }
                };
                return channelHandlers;
            }
        };

//        DemoClient dc = new DemoClient("localhost", 8080){
//
//            @Override
//            protected ChannelHandler[] initHandlers() {
//                return new ChannelHandler[]{
//                        new StringEncoder(),
//                        new StringDecoder(),
//                        new ClientDemoChannelHandler("Client-" + new Random(3000).nextInt(3000))
//                };
//            }
//        };

        dc.start();
    }
}
